package com.example.billw.controller;

import com.example.billw.entity.Bill;
import com.example.billw.entity.BillProvider;
import com.example.billw.entity.Provider;
import com.example.billw.mapper.BillMapper;
import com.example.billw.mapper.ProviderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Description TODO
 * @Author fantasy
 * @Date 2024/7/1 18:44
 **/

@Controller
public class BillController {

    @Autowired
    private BillMapper billMapper;
    @Autowired
    private ProviderMapper providerMapper;
    @GetMapping("/bills")
    public String billList(Model model, Bill bill) {
        List<Bill> bills = billMapper.getBills(bill);
        List<Provider> providers = providerMapper.getProviders(null);
        model.addAttribute("bills", bills);
        model.addAttribute("providers", providers);
        model.addAttribute("billName",bill.getBillName());
        model.addAttribute("pid",bill.getPid());
        model.addAttribute("pay",bill.getPay());
        return "bill/list";
    }
    /**
     * 删除账单
     * <p>
     * 此方法通过@RequestMapping注解映射到"/bill/delete/{id}"的HTTP请求，用于删除指定ID的账单。
     * 它接收一个路径变量id，该id代表账单的唯一标识。
     * 调用billMapper的deleteBill方法来执行删除操作，然后重定向到"/bills"页面。
     *
     * @param id 账单的ID，用于确定要删除的特定账单
     * @return "redirect:/bills" 字符串，指示视图应重定向到账单列表页面
     */
    @RequestMapping("/bill/delete/{id}")
    public String delete(@PathVariable("id") int id) {
        billMapper.deleteBill(id);
        return "redirect:/bills";
    }

    @GetMapping("/bill")
    public String toAddPage(Model model) {
        List<Provider> providers = providerMapper.getProviders(null);
        model.addAttribute("providers", providers);
        return "bill/add";
    }
    @PostMapping("/bill")
    public String add(Bill bill) {
        billMapper.addBill(bill);
        return "redirect:/bills";
    }

    @GetMapping("/bill/{bid}")
    public String viewBill(@PathVariable("bid") int bid, @RequestParam(value = "type", required = false, defaultValue = "view")String type, Model model) {
        BillProvider billProvider = billMapper.getBill(bid);
        model.addAttribute("billProvider", billProvider);
        if (type.equals("update")){
            List<Provider> providers = providerMapper.getProviders(null);
            model.addAttribute("providers", providers);
        }
        return "bill/"+type;
    }
}
